package com.czmh.etc.onlinepubsys.controller.mingchuang;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czmh.etc.onlinepubsys.entity.mingchuang.ApplyInfo;
import com.czmh.etc.onlinepubsys.entity.mingchuang.CurrentContext;
import com.czmh.etc.onlinepubsys.entity.mingchuang.EtcOrder;
import com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult;
import com.czmh.etc.onlinepubsys.model.EtcDevice;
import com.czmh.etc.onlinepubsys.model.EtcObuDTO;
import com.czmh.etc.onlinepubsys.model.EtcPayOrder;
import com.czmh.etc.onlinepubsys.request.mingchuang.GetStateRequest;
import com.czmh.etc.onlinepubsys.services.EtcOrderService;
import com.czmh.etc.onlinepubsys.services.EtcPayOrderService;
import com.czmh.etc.onlinepubsys.services.mingchuang.ICurrentContextService;
import com.czmh.etc.onlinepubsys.services.mingchuang.IEtcApplyService;
import com.czmh.etc.onlinepubsys.services.mingchuang.IEtcOrderService;
import com.czmh.etc.onlinepubsys.utils.DatetimeUtil;
import com.czmh.etc.onlinepubsys.utils.RedisUtil;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/{version}/api/mingchang/context")
@Api(tags = "车辆信息接口【新】- 铭创")
public class CurrentContextController {
    @Autowired
    private ICurrentContextService currentContextService;
    @Autowired
    private IEtcOrderService etcOrderService;
    @Autowired
    private IEtcApplyService etcApplyService;
    @Autowired
    private EtcOrderService orderService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private EtcPayOrderService etcPayOrderService;


    @PostMapping("/getState")
    @ApiOperation("查询当前用户的进行状态")
    public JSONResult getState(@RequestBody GetStateRequest param) {
        log.info("查询当前用户状态:{}", JSON.toJSONString(param));
        JSONResult result = new JSONResult();
        //发行方系统维护提示
        Object isRepair = redisUtil.get("isRepair");
        if(isRepair != null && isRepair.toString().equalsIgnoreCase("1")){
            Object repairTimeList = redisUtil.get("repairTimeList");
            if(repairTimeList != null){
                JSONArray jsonArray = JSON.parseArray(repairTimeList.toString());
                try {
                    Date current = new Date();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject object = (JSONObject) jsonArray.get(i);
                        Date beginTime = DatetimeUtil.parseSQLDate(object.getString("beginTime"), DatetimeUtil.STANDARD_DATETIME_PATTERN);
                        Date endTime = DatetimeUtil.parseSQLDate(object.getString("endTime"), DatetimeUtil.STANDARD_DATETIME_PATTERN);
                        if(beginTime.getTime() < current.getTime() && endTime.getTime() > current.getTime()){
                            result.setCode(JSONResult.FAIL);
                            result.setMessage("系统" + object.getString("beginTime") + "-" + object.getString("endTime") + "升级期间将无法正常发行ETC，请稍后再试！");
                            return result;
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        JSONObject json = new JSONObject();
        json.put("userId",param.getUserId());

        CurrentContext ctx = currentContextService.getByUserId(param.getUserId());
        if (ctx == null) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("当前用户不在申请流程中");
            return result;
        }
        Integer state = ctx.getState();
        json.put("payMode", ctx.getPayMode());
        json.put("state", state);
        json.put("type", ctx.getType());
        json.put("jsonData", ctx.getJsonData());
        json.put("etcUserType", ctx.getEtcUserType());
        EtcOrder order = etcOrderService.getByOrderNo(ctx.getOrderNo());
        json.put("orderPayState", order.getPayState());
        //上海接口对接业务需要查询订单对应的产品信息
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("deleteFlag", "0");
        queryMap.put("productSn", order.getBody());
        EtcDevice etcObuDTO = orderService.queryObject(queryMap);
        if (state == 0) {
            //通讯地址、收货人姓名、手机号码
            json.put("vehiclePlate", order.getVehPlate());
            json.put("vehicleColor", order.getVehColor());
            json.put("province", order.getProvince());
            json.put("city", order.getCity());
            json.put("region", order.getRegion());
            json.put("address", order.getAddress());
            json.put("username", order.getConsignee());
            json.put("phone", order.getPhone());
            json.put("orderNo", order.getOrderNo());
            if (null == etcObuDTO) {
                json.put("issuerName", null);
            }else{
                //发行方渠道配置选择
                String issueName = redisUtil.getIssueName();
                if(issueName != null){
                    json.put("issuerName", issueName);
                    etcObuDTO.setIssuerName(issueName);
                    orderService.updateObject(etcObuDTO);
                }else{
                    //产品发行方如果是西藏或者招商局统一走招商发行渠道
                    if(etcObuDTO.getIssuerName().equalsIgnoreCase("西藏") || etcObuDTO.getIssuerName().equalsIgnoreCase("招商")){
                        json.put("issuerName", "招商");
                    }else{
                        json.put("issuerName", etcObuDTO.getIssuerName());
                    }

                }
            }

        } else if (state > 1) {
            //车牌号、车牌色、车主证件号、车主证件类型、车主电话、车主姓名（识别的身份证姓名）、用户类型(个人/企业)
            ApplyInfo applyInfo = etcApplyService.get(ctx.getApplyId());
            if(applyInfo != null ){
                json.put("certifiNo", applyInfo.getCertifiNo());
                json.put("certifiType", applyInfo.getCertifiType());
                json.put("phone", applyInfo.getPhone());
                json.put("username", applyInfo.getUsername());
                json.put("ownerType", applyInfo.getOwnerType());
            }
            json.put("vehiclePlate", order.getVehPlate());
            json.put("vehicleColor", order.getVehColor());
            json.put("orderNo", order.getOrderNo());
            if (null == etcObuDTO) {
                json.put("issuerName", null);
            }else{
                json.put("issuerName", etcObuDTO.getIssuerName());
            }
        }
        //获取订金订单状态
        QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
        lambda.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda.eq(EtcPayOrder::getOrderSn, ctx.getOrderNo());
        lambda.eq(EtcPayOrder::getPayState, 1);
        int count = etcPayOrderService.count(wrapper);
        json.put("etcPayOrderState", count>=1);
        result.setRspData(json.toJSONString());
        return result;
    }
}
